import logging
from time import time

from flask import request, session
from flask_socketio import SocketIO

from utils.sql_utils.set import database, cursor, room_data


def init_user_chat(socket_io: SocketIO):

    @socket_io.on('message', namespace="/chat_room")
    def handle_message(message):
        sid = request.sid
        host = request.host
        uid = session['uid']
        name = session['name']
        head = session['head']
        data = message['data']

        if type(data) is not str or len(data) > 255 or len(data) == 0:
            return False

        database.connect()
        cursor.execute(f'insert into {room_data} (uid, mtime, mes, uhead, uname)'
                       f' values("{uid}", {int(time())}, "{data}", "{head}", "{name}");')
        database.commit()

        socket_io.emit(event="response",
                       data={'name': name, 'head': head, 'uid': uid, 'mes': data}, namespace="/chat_room")

    @socket_io.on('connect', namespace="/chat_room")
    def connect():
        host = request.host
        if 'uid' not in session.keys():
            print(session.keys())
            print(request.cookies.keys())
            logging.info(f"已拒绝来自 {host} 的websocket连接请求")
            return False
        uid = session['uid']
        socket_io.emit(event="join", data={'uid': uid}, namespace="/chat_room")
        logging.info(f"已与用户(uid:{uid},level:{session['level']})建立websocket连接 IP: {host} ")

    @socket_io.on('disconnect', namespace="/chat_room")
    def disconnect():
        host = request.host
        logging.info(f"用户(uid:{session['uid']},level:{session['level']})断开websocket连接 IP: {host} ")
